//============================================================================
//
// saCLI.js
// --------
//
// This module contains the code which hooks into the core API for the
// command line interface. All the exported functions here are called from
// the saParseArgs module. Core database functions are passed a callback
// which handles the data they return from SQLite
//
//============================================================================

var	sprintf = require('sprintf'),
	saCore = require('../core/saCore'),
	saGroupManager = require('../core/saGroupManager'),
	saHostManager = require('../core/saHostManager'),
	saZoneManager = require('../core/saZoneManager');

var myver = '0.0.0.1';

module.exports = {

//----------------------------------------------------------------------------
// GROUP FUNCTIONS

groupList: function(group) {
	
	// List available groups. Ignore any excess arguments

	saGroupManager.groupList(function(err, rows) {

		var i;	// counter

		if (rows.length === 0) {
			console.log('No groups exist.');
			process.exit(0);
		}
		else {
			console.log(sprintf.sprintf('%-33s %s', 'NAME', 'COMMENT'));

			// Print the group name and the comment. If there's
			// no comment the database gives us a 'null' so we
			// need to change that to an empty string

			for (i=0;i < rows.length; i++) {
				console.log(sprintf.sprintf('%-33s %s', rows[i].name,
				(rows[i].comment) ? rows[i].comment : ''));
			}

		}

	});

},

groupCount: function(group) {
				
	// How many hosts are in the given group? We don't do the work here,
	// this is just the presentation layer.

	saGroupManager.groupCount(group, function(err, res) {

		if (err) {
			throw(err);
		}

		if (res == undefined) {
			console.log('Group does not exist.');
		}
		else {
			console.log(res.host_count);
		}

	});
},

groupCreate: function(args) {

	// Call the group create function and handle the result via a callback.

	// args[0] is the name of the group
	// args[1] is an optional comment

	saGroupManager.groupCreate(args, function(err) {

		if (err) {

			// If the group exists, we'll get a constraint
			// error

			if (err.code === 'SQLITE_CONSTRAINT') {
				console.log("Group '" + args[0] + "' already exists.");
			}

			saCore.die("Failed to create group '" + args[0] + "'.");
		}
		else {
			console.log("Created group '" + args[0] + "'.");
		}

	});

},

groupComment: function(group, comment) {

	// Add or change the comment for an existing group

	saGroupManager.groupComment(group, comment, function(err) {

		if (err || this.changes == 0) {
			saCore.die("Failed to change comment for '" + group + "'.");
		}
		else {
			console.log("Set new comment for '" + group + "'.");
		}

	});

},

groupShow: function(group) {

	// Show hosts which belong to the named group

	var i;	// counter

	saGroupManager.groupShow(group, function(err, rows) {
		
		if (err) {
			throw(err);
		}

		if (rows.length === 0) {
			console.log('No hosts in group, or group does not exist.');
		}
		else {

			for (i=0; i < rows.length; i++) {
				console.log(rows[i].hostname);
			}
		}

	});
},

groupDelete: function(group) {

	// Remove a group and, via foreign key cascades in the database, all
	// hosts belonging to that group, all zones belonging to those hosts,
	// and all audit data belonging to those zones.

	saGroupManager.groupDelete(group, function(err, res) {

		if (this.changes > 0) {
			console.log("Deleted group '" + group + "'.");
		}
		else {
			saCore.die("Failed to delete group '" + group + "'.");
		}

	});

},

groupRename: function(group, new_name) {

	// Call the method which renames a group, and handle whatever it returns
	// with.

	saGroupManager.groupRename(group, new_name, function(err) {

		if (err || this.changes == 0) {
			saCore.die("Unable to rename group '" + group + "'.");
		}
		else {
			console.log("Renamed '" + group + "' to '" + new_name + "'.");
		}

	});

},

groupExport: function(group) {

	saGroupManager.groupExport(group);
},

groupImport: function(group, filename) {

	saGroupManager.groupImport(group, filename);
},

//----------------------------------------------------------------------------
// HOST FUNCTIONS

hostList: function() {

	// Call the method which lists known hosts and present the data

	saHostManager.hostList(function(err, res) {
		console.log(sprintf.sprintf('%-33s %s', 'HOST', 'GROUP'));

		// Print the host name and the group each host belongs to

		for (i=0;i < res.length; i++) {
			console.log(sprintf.sprintf('%-33s %s', res[i].host,
			res[i].groupname));
		}

	});

},

hostCheckpoints: function(group, host) {

	// Call the method which pulls host checkpoints out of the database, and
	// handles what it passes back.

	// reassemble the group/host string for shorthand

	var ghs = "'" + group + '/' + host + "'";

	saHostManager.hostCheckpoints(group, host, function(err, res) {

		if (err) {
			throw('Error retrieving checkpoint info for ' + ghs + '.');
		}
		else if (res.length === 0) {
			console.log('No checkpoint information for ' + ghs + '.');
		}
		else {
			console.log('Checkpoints for ' + ghs);

			for (i=0; i < res.length; i++) {
				date = new Date(res[i].timestamp);
				console.log(date);
			}

		}

	});

},

hostDelete: function(group, host) {
	
	// Call the delete host method and handle its response.

	// reassemble the group/host string for shorthand

	var ghs = "'" + group + '/' + host + "'";

	saHostManager.hostDelete(group, host, function(err, res) {

		if (err) {
			throw('Error deleting ' + ghs);
		}
		else if (this.changes === 0) {
			saCore.die('Failed to delete ' + ghs + '.');
		}
		else {
			console.log('Deleted ' + ghs + '.');
		}

	});

},

hostMove: function(group, host, target) {
	
	// Call the host move method and present its response.

	var shand = "'" + group + '/' + host + "' to '" + target + "'.";

	saHostManager.hostMove(group, host, target, function(err, res) {
		
		if (err) {
			throw('Error moving ' + shand);
		}

		if (this.changes === 0) {
			console.log('Unable to move ' + shand);
		}
		else {
			console.log('Moved ' + shand);
		}

	});
},

hostZones: function(group, host) {
	
	// Call the method which lists a host's local zones and present the
	// output.

	saHostManager.hostZones(group, host, function(err, res) {

		if (err) {
			throw('Error querying ' + group + '/' + host);
		}
		else {

			for (var i =0; i < res.length; i++) {
				console.log(res[i]['zone_name']);
			}

		}
	});

},

hostImport: function(group, filename) {

	// Call the function which imports a JSON file to the database. This is
	// a lot of code, so it gets its own module, which only needs loading
	// here.

	saHostImport = new require('../core/saHostImport');

	saHostImport.doImport(group, filename, function(err, res) {
	});

},


//----------------------------------------------------------------------------
// ZONE FUNCTIONS

zoneParent: function(zone) {

	// Call the function which returns a list of hosts who have a local zone
	// with the given name

	saZoneManager.zoneParent(zone, function(err, res) {

		if (err) {
			throw('Error querying zone table.');
		}
		else {

			if (res.length === 0) {
				console.log('Zone does not exist, or is orpahned.');
			}
			else {
				for (var i =0; i < res.length; i++) {
					console.log(res[i]['hostname']);
				}
			}

		}

	});

},


//----------------------------------------------------------------------------
// INFO

info: function() {
	
	var saInfo = require("../core/saInfo");
	var chunk,
		piece;

	console.log('\nFourdit Command-Line Interface');
	console.log('------------------------------\n');
	console.log(sprintf.sprintf('%15s: %s', 'Version', myver));

	for (chunk in saInfo) {

		console.log('\n' + chunk + '\n' + chunk.replace(/./g, '-'));

		for (piece in saInfo[chunk]) {
			console.log(sprintf.sprintf('%15s: %s', piece,
			saInfo[chunk][piece]));
		}

	}

	console.log();
}

} // close exports
